package pl.balon.gwt.diagrams.client.connection.pointwidget;

import pl.balon.gwt.diagrams.client.connection.AbstractConnection;
import pl.balon.gwt.diagrams.client.connection.pointwidget.MoveablePointWidgetImpl.State;

import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.user.client.Event;


public class MovePointFactoryImpl implements MovePointFactory {
	private static MovePointFactoryImpl instance;

	public static MovePointFactory getInstance() {
		if(instance==null )
			instance=new MovePointFactoryImpl();
		return instance;
	}

	private MovePointFactoryImpl() {
		// TODO Auto-generated constructor stub
	}
	 public MoveablePointWidget createMovablePointWidget(AbstractConnection handler) {
		 MoveablePointWidgetImpl w = new MoveablePointWidgetImpl(handler);
			w.addMouseOverHandler(new MouseOverHandler() {
				public void onMouseOver(MouseOverEvent event) {
					MoveablePointWidgetImpl m = (MoveablePointWidgetImpl) event.getSource();
					m.setFocus(true);
					m.setState(State.ONMOUSEOVER);
				}
			});
			w.addMouseOutHandler(new MouseOutHandler() {
				public void onMouseOut(MouseOutEvent event) {
					MoveablePointWidgetImpl m = (MoveablePointWidgetImpl) event.getSource();
					m.setFocus(false);
					m.setState(State.FREE);
				}
			});
			w.addMouseOutHandler(new PositionUpdateMouseOutHandler());
			w.addMouseUpHandler(new MouseUpHandler() {
				public void onMouseUp(MouseUpEvent event) {
					if(event.getNativeButton() == Event.BUTTON_MIDDLE) {
						MoveablePointWidget widget= (MoveablePointWidget) event.getSource();
						widget.getConnection().fireEvent(new MoveablePointWidgetDeleteEvent(widget));
					}
				}
			});
			w.addKeyPressHandler(new KeyPressHandler() {
				public void onKeyPress(KeyPressEvent event) {
					if(event.getCharCode() == KeyCodes.KEY_DELETE) {
						MoveablePointWidget widget= (MoveablePointWidget) event.getSource();
						widget.getConnection().fireEvent(new MoveablePointWidgetDeleteEvent(widget));
					}
					event.stopPropagation();
				}
			});
			return w;
	}
}
